#include "panelcost.h"
#include "dlgeditcost.h"
#include "pm/manager.h"
#include <boost/foreach.hpp>

PanelCost::PanelCost(wxWindow* parent)
: PanelCostGui(parent)
{
	m_listCost->InsertColumn(COL_NAME,      _("Name"));
	m_listCost->InsertColumn(COL_UNIT_COST, _("Unit cost"), wxLIST_FORMAT_RIGHT);
	m_listCost->InsertColumn(COL_QUANTITY,  _("Quantity"),  wxLIST_FORMAT_RIGHT);
	m_listCost->InsertColumn(COL_COST,      _("Cost"),      wxLIST_FORMAT_RIGHT);
	m_listCost->InsertColumn(COL_DATE,      _("Date"));
	m_listCost->InsertColumn(COL_TASK,      _("Task"));
	
	wxTheApp->Connect(pmEVT_PROJECT_LOADED, wxCommandEventHandler(PanelCost::OnProjectLoaded),  NULL, this);
	
	pmConnect(pmEVT_COST_ADDED,   pm::Cost, PanelCost::OnCostAdded);
	pmConnect(pmEVT_COST_UPDATED, pm::Cost, PanelCost::OnCostUpdated);
}

void PanelCost::AddCost(const pm::CostInfo& cost)
{
	long item = m_listCost->InsertItem(m_listCost->GetItemCount(), wxEmptyString);
	SetCost(item, cost);
}

void PanelCost::SetCost(long item, const pm::CostInfo& cost)
{
	m_listCost->SetItem(item, COL_NAME,      cost.name());
	m_listCost->SetItem(item, COL_UNIT_COST, wxString::Format(wxT("%.2f"), cost.unit_cost()));
	m_listCost->SetItem(item, COL_QUANTITY,  wxString::Format(wxT("%.2f"), cost.quantity()));
	m_listCost->SetItem(item, COL_COST,      wxString::Format(wxT("%.2f"), cost.cost()));
	m_listCost->SetItem(item, COL_DATE,      cost.date().FormatISODate());
	m_listCost->SetItem(item, COL_TASK,      cost.task_name());
	m_listCost->SetItemData(item, cost.id());
}

void PanelCost::OnProjectLoaded(wxCommandEvent& event)
{
	event.Skip();
	wxLogMessage(wxT("PanelCost::OnProjectLoaded(%d)"), event.GetInt());
	
	m_listCost->DeleteAllItems();
	pm::GetCostsByProject crit(event.GetInt());
	pm::select(crit);
	
	BOOST_FOREACH(const pm::CostInfo& cost, crit.m_result) {
		AddCost(cost);
	}
}

void PanelCost::OnCostAdded(pmEvent<pm::Cost>& event)
{
	event.Skip();
	wxLogMessage(wxT("PanelCost::OnCostAdded()"));
	
	pm::CostInfo costInfo;
	pm::get_by_id(event.GetContent().id(), costInfo);
	AddCost(costInfo);
}

void PanelCost::OnCostUpdated(pmEvent<pm::Cost>& event)
{
	event.Skip();
	const pm::Cost& cost = event.GetContent();
	long item = m_listCost->FindItem(-1, cost.id());
	assert(item != wxNOT_FOUND);

	pm::CostInfo costInfo;
	pm::get_by_id(cost.id(), costInfo);
	SetCost(item, costInfo);
}

void PanelCost::OnAddCost( wxCommandEvent& WXUNUSED(event) )
{
	DlgNewCost dlg(this);
	dlg.ShowModal();
}

void PanelCost::OnItemActivated( wxListEvent& event )
{
	int id = m_listCost->GetItemData(event.GetIndex());
	wxLogMessage(wxT("PanelCost::OnItemActivated(id = %d)"), id);
	
	pm::Cost cost;
	if (pm::get_by_id(id, cost) == false) {
		// TODO : show error
		return;
	}
	
	DlgUpdateCost dlg(this, cost);
	dlg.ShowModal();
}
